from django.db import models
from django.contrib.auth.models import AbstractUser

from drf_shop_admin.utils.models import BaseModel

# Create your models here.
class User(AbstractUser):
    """
    用户表
    """
    GENDER_CHOICES = (
        (0, '男'),
        (1, '女'),
        (2, '保密')
    )
    EDUCATION_CHOICES = (
        ('doctor', '博士'),
        ('masters', '硕士'),
        ('bachelor', '本科'),
        ('speciality', '专科'),
        ('high_school', '高中'),
        ('junior', '初中'),
        ('primary_school', '小学'),
        ('secrecy', '保密'),
    )
    IS_ACTIVE_CHOICES = (
        (True, '是'),
        (False, '否')
    )
    gender = models.SmallIntegerField('性别', choices=GENDER_CHOICES, default=2, null=False, blank=False)
    tel = models.CharField('手机号', max_length=11, blank=False, null=False, unique=True)
    education = models.CharField('学历', max_length=15, choices=EDUCATION_CHOICES, default='secrecy', blank=False, null=False)
    hobby = models.CharField('兴趣', max_length=100, blank=True)
    introduction = models.TextField('简介', blank=True)
    qq_open_id = models.CharField('qq官方唯一编号信息', max_length=32, blank=True, null=False)
    email_code = models.CharField('新用户注册邮件激活唯一校验码', max_length=13, null=True, default=None)
    is_active = models.BooleanField('新用户是否已经通过邮箱激活帐号', choices=IS_ACTIVE_CHOICES, default=False)
    role = models.ManyToManyField('system.Roles', blank=True, verbose_name='用户角色', related_name='user')

    objects = models.Manager()

    def __str__(self):
        return self.username

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        ordering = ['id']

    def _get_user_permissions(self):
        """获取用户权限"""
        permissions = list(filter(None, set(self.role.values_list('permissions__sign', flat=True))))
        return permissions

    def get_user_info(self):
        """获取用户信息"""
        user_info = {
            'id': self.pk,
            'username': self.username,
            'tel': self.tel,
            'gender': self.gender,
            'email': self.email,
            'permissions': self._get_user_permissions(),
            'introduction': self.introduction
        }
        return user_info

class Carts(BaseModel):
    """
    用户购物车
    """
    info = models.TextField('详细信息')
    user = models.OneToOneField('User', on_delete=models.CASCADE, related_name='cart')
    order = models.ManyToManyField('orders.Orders', blank=True, verbose_name='购物车订单')

    objects = models.Manager()

    def __str__(self):
        return self.user.username

    class Meta:
        verbose_name = '用户购物车'
        verbose_name_plural = verbose_name
        ordering = ['id']